<template>
  <div class="app-container">
    <h2 style="text-align: center">发布新课程</h2>
    <el-steps
      :active="2"
      align-center
      style="margin-bottom: 40px"
      process-status="wait"
    >
      <el-step title="填写基本信息"></el-step>
      <el-step title="创造课程大纲"></el-step>
      <el-step title="发布课程"></el-step>
    </el-steps>
    <el-button type="text" @click="openAddChapterDialog">添加章节</el-button>
    <ul class="chanpterList">
      <li v-for="chapter in chapterNestedList" :key="chapter.id">
        <p>
          {{ chapter.title }}
          <span class="acts">
            <el-button type="text" @click="openAddVideoDialog(chapter.id)"
              >添加课时</el-button
            >
            <el-button type="text" @click="openEditChapterDialog(chapter.id)"
              >编辑</el-button
            >
            <el-button type="text" @click="deleteChapter(chapter.id)"
              >删除</el-button
            >
          </span>
        </p>
        <ul class="chanpterList videoList">
          <li v-for="video in chapter.children" :key="video.id">
            <p>
              {{ video.title }}
              <span class="acts">
                <el-button type="text" @click="openEditVideoDialog(video.id)"
                  >编辑</el-button
                >

                <el-button type="text" @click="deleteVideo(video.id)"
                  >删除</el-button
                >
              </span>
            </p>
          </li>
        </ul>
      </li>
    </ul>

    <el-button type="default" @click="privious()">上一步</el-button>
    <el-button type="primary" @click="next()">下一步</el-button>
    <!-- 添加/编辑章节表单对话框 -->
    <el-dialog :title="dialogChapterTiter" :visible.sync="dialogChapterVisible">
      <el-form
        :model="video"
        :rules="chapterRules"
        ref="chapterFrom"
        label-width="120px"
      >
        <el-form-item label="章节标题" prop="title">
          <el-input v-model="chapter.title" />
        </el-form-item>
        <el-form-item label="章节排序" prop="sort">
          <el-input-number
            v-model="chapter.sort"
            controls-position="right"
            :min="0"
          ></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogChapterVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitChapter">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加/编辑课时表单对话框 -->
    <el-dialog :title="dialogVideoTitle" :visible.sync="dialogVideoVisible">
      <el-form
        :model="video"
        :rules="videoRules"
        ref="videoFrom"
        label-width="120px"
      >
        <el-form-item label="课时标题" prop="title">
          <el-input v-model="video.title" />
        </el-form-item>
        <el-form-item label="课时排序" prop="sort">
          <el-input-number
            v-model="video.sort"
            controls-position="right"
            :min="0"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="是否免费">
          <el-radio v-model="video.isFree" :label="1">免费</el-radio>
          <el-radio v-model="video.isFree" :label="0">收费</el-radio>
        </el-form-item>
        <el-form-item label="上传视频">
          <el-upload
            class="upload-demo"
            :action="`${BASE_URL}/vod/upload`"
            :on-success="handleUpload"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
          >
            <el-button type="primary" size="mini">上传视频</el-button>
            <el-tooltip class="item" effset="dark" placement="right">
              <div slot="content">
                最大支持1G,<br />
                支持3GP、ASF、AVI、DAT、DV、FLV、F4V、<br />
                GIF、M2T、M4V、MJ2、MJPEG、MKV、MOV、<br />
                MP4、MPE、MPG、MPEG、MTS、oGG、QT、RM、<br />
                RMVB、SWF、TS、VOB、WMV、WEBM等视频格式上传<br />
              </div>
              <i class="el-icon-question"></i>
            </el-tooltip>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVideoVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitVideo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
  <script>
import chapterApi from "@/api/chapter";
import videoApi from "@/api/video";
import vodApi from '@/api/vod'
export default {
  data() {
    return {
      BASE_URL: process.env.BASE_API, //获取dev配置文件中的api地址
      fileList: [],
      courseId: "", //课程id
      chapterNestedList: [], //课程大纲列表
      dialogChapterVisible: false, //课程章节对话框
      dialogVideoVisible: false, //课程课时对话框
      chapter: {
        courseId: "",
        title: "",
        sort: 0,
      },
      video: {
        courseId: "",
        chapterId: "",
        title: "",
        videoSourceId: "",
        videoOriginalName: "",
        sort: 0,
        isFree: 0,
      },
      dialogChapterTiter: "", //课程章节对话框标题
      dialogVideoTitle: "", //课程课时对话框标题
      chapterRules: {
        //章节表单验证规则
        title: [
          { required: true, message: "请输入章节标题", trigger: "blur" },
          { max: 50, message: "长度最大为50个字符", trigger: "blur" },
        ],
        sort: [
          { type: "number", message: "排序必须是数字值", trigger: "blur" },
          { required: true, message: "请输入讲师序号", trigger: "blur" },
        ],
      },
      videoRules: {
        //课时表单验证规则
        title: [
          { required: true, message: "请输入课时标题", trigger: "blur" },
          { max: 50, message: "长度最大为50个字符", trigger: "blur" },
        ],
        sort: [
          { type: "number", message: "排序必须是数字值", trigger: "blur" },
          { required: true, message: "请输入讲师序号", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    //初始化课程
    this.init();
  },
  methods: {
    handleRemove(file, fileList) {
      console.log(file, fileList);
      //调用api接口删除云端视频
      vodApi.deleteVodVideo(this.video.videoSourceId).then(res=>{
            //清空视频信息
            this.video.videoSourceId=''
            this.video.videoOriginalName=''
            this.fileList=[]
            //提示成功信息
            this.$message({
                type: 'success',
                message: '删除成功!'
            })
        })
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`想要重新上传视频，请删除已上传的视频`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
    //视频上传成功之后
    handleUpload(response, file, fileList) {
      console.log(response);
      console.log(file);
      console.log(fileList);
      //获取视频编号
      this.video.videoSourceId = response.data.videoSourceId;
      //获取视频原始名称
      this.video.videoOriginalName = file.name;
    },
    //上一步
    privious() {
      this.$router.push({ path: `/course/info/${this.courseId}` });
    },
    //下一步
    next() {
      this.$router.push({
        name: "CourseInfoPublish",
        params: { id: this.courseId },
      });
    },
    //打开添加课时对话框
    openAddVideoDialog(chapterId) {
      this.dialogVideoTitle = "添加课时";
      this.dialogVideoVisible = true;
      //为课时的章节赋值
      this.video.chapterId = chapterId;

      //清空表单数据
      this.video = {
        id: "",
        courseId: "",
        chapterId: chapterId,
        title: "",
        videoSourceId: "",
        videoOriginalName: "",
        sort: 1,
        isFree: 0,
      };
      this.fileList = [];
    },
    deleteChapter(chapterId) {
      //先弹出对话框询问是否要删除
      this.$confirm("您确定要删除章节吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //调用删除章节的api
          chapterApi.deleteById(chapterId).then((res) => {
            //删除成功,提示信息
            this.$message({
              type: "success",
              message: "删除成功",
            });
            //重新加载数据
            this.init();
          });
        })
        .catch(() => {});
    },
    deleteVideo(videoId) {
      //先弹出对话框询问是否要删除
      this.$confirm("您确定要删除章节吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //调用删除章节的api
          videoApi.deleteById(videoId).then((res) => {
            //删除成功,提示信息
            this.$message({
              type: "success",
              message: "删除成功",
            });
            //重新加载数据
            this.init();
          });
        })
        .catch(() => {});
    },
    //更新课程章节
    undateChapter() {
      //调用更新课程章节的APi
      chapterApi.undateChapter(this.chapter).then((res) => {
        //提示更新成功信息
        this.$message({
          type: "success",
          message: "添加成功",
        });
        //关闭课程章节对话框
        this.dialogChapterVisible = false;
        //重置视频上传列表
        this.fileList = [];
        //重新加载列表
        this.init();
      });
    },
    //更新课时
    undateVideo() {
      //调用更新课程课时的APi
      videoApi.undateVideo(this.video).then((res) => {
        //提示更新成功信息
        this.$message({
          type: "success",
          message: "更新成功",
        });
        //关闭课程章节对话框
        this.dialogVideoVisible = false;

        //重新加载列表
        this.init();
      });
    },
    //打开编辑课程章节对话框
    openEditChapterDialog(chapterId) {
      this.dialogChapterTiter = "编辑章节";
      //根据章节id获取章节信息
      chapterApi.getChapter(chapterId).then((res) => {
        this.chapter = res.data;
      });
      //打开章节对话框
      this.dialogChapterVisible = true;
    },
    //打开编辑课课时的对话框
    openEditVideoDialog(videoId) {
      this.dialogVideoTitle = "编辑课时";
      this.fileList = [];
      //根据章节id获取课时信息
      videoApi.getVideoById(videoId).then((res) => {
        this.video = res.data;
        if (this.video.videoOriginalName) {
          //为上传视频列表赋值
          this.fileList = [{ name: this.video.videoOriginalName }];
        }
        //打开对话框
        this.dialogVideoVisible = true;
      });
    },
    //提交章节对话框表单数据
    submitChapter() {
      //进行数据的合法性校验
      this.$refs["chapterFrom"].validate((valid) => {
        if (valid) {
          //验证通过
          //判断执行的是添加还是更新
          if (this.chapter.id) {
            //调用更新方法
            this.undateChapter();
          } else {
            //调用添加讲师方法
            this.addChapter();
          }
        } else {
          //格式校验失败
          console.log("error submit!!");
          return false;
        }
      });
    },
    //提交课时表单对话框
    submitVideo() {
      //进行数据的合法性校验
      this.$refs["videoFrom"].validate((valid) => {
        if (valid) {
          //验证通过
          //判断执行的是添加还是更新
          if (this.video.id) {
            //调用更新方法
            this.undateVideo();
          } else {
            //调用添加讲师方法
            this.addVideo();
          }
        } else {
          //格式校验失败
          console.log("error submit!!");
          return false;
        }
      });
    },
    //添加课时
    addVideo() {
      //为课程id赋值
      this.video.courseId = this.courseId;
      //调用添加课时的Api
      videoApi.addVideo(this.video).then((res) => {
        //提示更新成功信息
        this.$message({
          type: "success",
          message: "添加成功",
        });
        //关闭课程章节对话框
        this.dialogVideoVisible = false;

        //重新加载列表
        this.init();
      });
    },
    //添加章节
    addChapter() {
      //调用添加课程章节的api

      //为课程id赋值
      this.chapter.courseId = this.courseId;
      chapterApi.addChapter(this.chapter).then((res) => {
        //提示成功信息，关闭对话框
        //提示成功信息
        this.$message({
          type: "success",
          message: "添加成功",
        });
        //关闭对话框
        this.dialogChapterVisible = false;
        //更新列表数据
        this.init();
      });
    },
    //打开添加章节对话框
    openAddChapterDialog() {
      this.dialogChapterTiter = "添加章节";
      this.dialogChapterVisible = true;

      //初始化章节表单信息
      this.chapter = {
        title: "",
        sort: 0,
        id: "",
      };
    },
    //初始化课程大纲
    init() {
      if (this.$route.params && this.$route.params.id) {
        //根据课程id获取当前要更新的课程信息
        //绑定到页面
        this.courseId = this.$route.params.id;
        this.getChapterTree(this.courseId);
      } else {
      }
    },
    //获取课程大纲
    getChapterTree(courseId) {
      chapterApi.getTreeList(courseId).then((res) => {
        console.log(res);
        this.chapterNestedList = res.data;
      });
    },
  },
};
</script>
  <style scoped>
.chanpterList {
  position: relative;
  list-style: none;
  margin: 0;
  padding: 0;
}
.chanpterList li {
  position: relative;
}
.chanpterList p {
  float: left;
  font-size: 20px;
  margin: 10px 0;
  padding: 10px;
  height: 70px;
  line-height: 50px;
  width: 100%;
  border: 1px solid #ddd;
}
.chanpterList .acts {
  float: right;
  font-size: 14px;
}

.videoList {
  padding-left: 50px;
}
.videoList p {
  float: left;
  font-size: 14px;
  margin: 10px 0;
  padding: 10px;
  height: 50px;
  line-height: 30px;
  width: 100%;
  border: 1px dotted #ddd;
}
</style>